package spring_Proxydemo1.Proxydemo1;


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

//动态代理:
public class ProxyFactory {
   public Object target;

    public ProxyFactory(Object target) {
        this.target = target;
    }
    public Object getProxy() {

        /*
         * ClassLoader:
         * Class<?>[] interfaces:
         *  InvocationHandler h:
         * */
        ClassLoader classLoader = this.getClass().getClassLoader();
        Class<?>[] interfaces = target.getClass().getInterfaces();
    /*    InvocationHandler h=new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {

                //选中目标进行try/catch快捷键:ctrl+alt+t
                Object result = null;
                try {
                    System.out.println("方法前，添加另外的功能");
                    result = method.invoke(target, objects);
                    System.out.println("方法后，添加另外的功能");
                    System.out.println("finish");
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    System.out.println("执行完毕");
                }
                return result;
            }
        };
        return Proxy.newProxyInstance(classLoader,interfaces,h);
    }*/


        //lambda表达式优化
        InvocationHandler h=(o, method, objects)->{
                //选中目标进行try/catch快捷键:ctrl+alt+t
                Object result = null;
                try {
                    System.out.println("方法前，添加另外的功能");
                    result = method.invoke(target, objects);
                    System.out.println("方法后，添加另外的功能");
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    System.out.println("执行完毕");
                }
                return result;
        };
        return Proxy.newProxyInstance(classLoader,interfaces,h);
    }
}
